package com.googlecode.jlogalizerweb.mq.listener;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.log4j.spi.LoggingEvent;

import com.googlecode.jlogalizerweb.utils.FileAppendUtils;
import com.googlecode.jlogindexer.document.LogDocument;
import com.googlecode.jlogindexer.utils.ActiveMQMessageUtils;
import com.googlecode.jlogindexer.utils.PropertyUtil;
import com.googlecode.jlogindexer.utils.SolrUtils;

public class JLogMessageListener implements MessageListener {

	private SolrUtils solrUtils;
	private FileAppendUtils fileAppendUtils;
	
	public SolrUtils getSolrUtils() {
		return solrUtils;
	}

	public void setSolrUtils(SolrUtils solrUtils) {
		this.solrUtils = solrUtils;
	}

	
	public void onMessage(Message message) {
		System.out.println("MESSAAAAAAAAAAAAAAAGEEEEEEEEE RECEIVED>>>>>>>>>>>>>>>>>>>>>"+message);
		if (message instanceof TextMessage) {
			try {
				System.out.println(((TextMessage)message).getText());
				
				Calendar today = Calendar.getInstance();
				
				fileAppendUtils.appendToFile(((TextMessage)message).getText(), new File(PropertyUtil.getInstance().getValue("INPUT_PATH"),today.get(Calendar.DAY_OF_MONTH)+"_"+today.get(Calendar.MONTH)+".log"));
				
			} catch (JMSException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else if (message instanceof ActiveMQObjectMessage){
			LoggingEvent event;
			try {
				event = (LoggingEvent)((ActiveMQObjectMessage)message).getObject();
				LogDocument logDocument=ActiveMQMessageUtils.convertActiveMQMessageToLogDocument(event);
				solrUtils.addDocumentToSolr(logDocument);
				System.out.println("Received log [" + event.getLevel() + "]: "+ event.getMessage());
			} catch (JMSException e) {
				e.printStackTrace();
			}
			
		}
		else {
			throw new IllegalArgumentException("Log Message must be of type TextMessage");
		}
	}

}

	